using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace Thermerators
{
    class TMP36
    {
        private AnalogInput Tmp36;
        private double[] samples;
        private int curSample;

        public TMP36(AnalogInput input, int sampleSize)
        {
            Tmp36 = input;
            this.samples = new double[sampleSize];
            this.curSample = 0;
        }

        public double read()
        {
            double voltage = Tmp36.Read() * 3.3 / 1024;
            double tempC = (voltage - 0.5) * 100;
            this.samples[curSample++] = tempC;
            if (curSample == this.samples.Length)
                this.curSample = 0;
            if (this.samples[curSample] == 0 && this.curSample == 1)
            {
                for (int i = 1; i < this.samples.Length; i++)
                    this.samples[i] = this.samples[0];
            }
            return getAvergaeSamples();
        }

        private double getAvergaeSamples()
        {
            double avg = 0;
            for (int i = 0; i < this.samples.Length; i++)
                avg += this.samples[i];
            return avg / this.samples.Length;
        }

        public double convertToF(double tempC)
        {
            return (tempC * 9 / 5) + 32;
        }
    }
}
